package com.fmsz.xmly.adapters;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/28.
 *
 */

public class CommentAdapter<D> extends RecyclerView.Adapter<CommentAdapter.ViewHolder>{
    private Map<Class<?>,Pair<Integer,Integer>> map;
    private List<D> list;
    private Context context;

    public CommentAdapter(Map<Class<?>, Pair<Integer, Integer>> map, List<D> list, Context context) {
        this.map = map;
        this.list = list;
        this.context = context;
    }

    public CommentAdapter(List<D> list, Context context,Integer layoutId,Integer variable) {
        this.list = list;
        this.context = context;
        map = new HashMap<>();
        map.put(null,new Pair<>(layoutId,variable));
    }

    @Override
    public int getItemViewType(int position) {
        if (map.size()==1) {
            return map.get(null).first;
        }else{
            return map.get(list.get(position).getClass()).first;
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(context),viewType,parent,false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Pair<Integer,Integer> pair;
        if (map.size()==1) {
            pair = map.get(null);
        }else{
            pair = map.get(list.get(position).getClass());
        }
        holder.binding.setVariable(pair.second,list.get(position));
    }
    public void add(D d){
        if (d == null) {
            return;
        }
        add(list.size(),d);
    }

    public void add(int position, D d) {
        if (position>list.size()) {
            position = list.size();
        }
        list.add(position,d);
        notifyItemInserted(position);
    }
    public void addAll(List<? extends D> list){
        if (list == null) {
            return;
        }
        addAll(this.list.size(),list);
    }

    public void addAll(int position, List<? extends D> list) {
        this.list.addAll(position,list);
        notifyItemRangeInserted(position,list.size());
    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        private ViewDataBinding binding;

        public ViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
